package com.example.voting_master.schedule;

import com.alibaba.fastjson2.JSON;
import com.example.voting_master.entity.UserVoteLog;
import com.example.voting_master.service.UserVoteLogService;
import com.example.voting_master.util.RedisCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.voting_master.constant.RedisConstant.LogWaitingInsertDB;

@Component
@Slf4j
public class LogInsertDBSchedule {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private UserVoteLogService userVoteLogService;

    @Scheduled(fixedDelay = 23000)
    private void log_insert_DB() {
        try {
            List<Object> objectList = redisCacheUtil.lGet(LogWaitingInsertDB, 0, 800);
            Collection<UserVoteLog> uvl_collection = objectList.stream()
                    .map(obj -> JSON.parseObject(obj.toString(), UserVoteLog.class))
                    .collect(Collectors.toCollection(ArrayList::new));
            if (!uvl_collection.isEmpty() && userVoteLogService.saveBatch(uvl_collection)) {
                if (redisCacheUtil.lRemove(LogWaitingInsertDB, uvl_collection.size()))
                    log.info("数据库批写入成功:{},时间:{}", uvl_collection, new Date().getTime());
            }
        } catch (Exception e) {
            log.error("数据库批写入失败:{},时间:{}",e,new Date().getTime());
        }
    }
}
